import { AvatarDropdown, AvatarName, Footer, Question, SelectLang } from '@/components';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import React from 'react';
import defaultSettings from '../config/defaultSettings';
import { message } from 'antd';
import { getToken } from '@/utils/auth';
// import { getInitialState } from '@umijs/max';
import './global.less';
import { RequestConfig } from '@umijs/max';
const loginPath = '/user/login';

// 定义 API 接口类型
declare namespace API {
  type UserInfo = {
    name?: string;
    avatar?: string;
    userid?: string;
    permissions?: string[];
  };
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = getToken();
    if (!token) {
      throw new Error('No token found');
    }
    // 从本地存储获取用户信息
    const cachedUserInfo = localStorage.getItem('user_info');
    const cachedMenus = localStorage.getItem('menus');

    if (cachedUserInfo) {
      const userInfo = JSON.parse(cachedUserInfo);
      // 确保用户信息中包含菜单数据
      if (!userInfo.menus && cachedMenus) {
        userInfo.menus = JSON.parse(cachedMenus);
      }
      return userInfo;
    }

    // 如果本地没有，从服务器获取
    const msg = await getUserInfo();
    if (msg.code === 200 && msg.data) {
      localStorage.setItem('user_info', JSON.stringify(msg.data));
      return msg.data;
    }
    throw new Error(msg.msg || 'Failed to get user info');
  } catch (error) {
    console.error('Error fetching user info:', error);
    history.push(loginPath);
  }
  return undefined;
};

// 全局初始化数据配置
export async function getInitialState(): Promise<{
  currentUser?: API.CurrentUser;
  menus?: any[];
}> {
  try {
    // 如果是登录页面，不执行
    if (location.pathname === '/user/login') {
      return {};
    }

    const token = localStorage.getItem('token');
    if (!token) {
      history.push('/user/login');
      return {};
    }

    // 获取用户信息和菜单数据
    const userInfo = await fetch('/api/userSystem/getUserInfo', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }).then(res => res.json());

    // 添加日志
    console.log('获取到的用户信息:', userInfo);

    // 获取菜单数据
    const menuResponse = await fetch('/api/sys/resource', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'institutionId': localStorage.getItem('institutionId'),
        'institutionRoleId': localStorage.getItem('institutionRoleId'),
        'departmentId': localStorage.getItem('departmentId'),
        'positionId': localStorage.getItem('positionId')
      }
    });

    const menuData = await menuResponse.json();
    console.log('获取到的菜单数据:', menuData);

    if (menuData.code !== 200) {
      console.error('菜单数据获取失败:', menuData.msg);
      return {
        currentUser: userInfo.data
      };
    }

    return {
      currentUser: userInfo.data,
      menus: menuData.data
    };
  } catch (error) {
    console.error('获取初始化数据失败:', error);
    history.push('/user/login');
    return {};
  }
}

// 请求配置
export const request: RequestConfig = {
  timeout: 10000,
  requestInterceptors: [
    (url: string, options: any) => {
      console.log('url1111111111111111:', url);
      console.log('options:', options);
      const token = getToken();
      return {
        url,
        options: {
          ...options,
          headers: {
            ...options.headers,
            'dhcc-auth': token || '',
          },
        },
      };
    },
  ],
};
